<template>
  <!--  请在index.html中引入gaodeAPI在线js
  <script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=mykey&plugin=AMap.Autocomplete,AMap.PlaceSearch"></script>
-->
  <div class="gaodePoiSearch">
    <div class="info">
      <div class="input-item">
        <el-input
          placeholder="地点搜索......"
          id="tipinput"
          class="input-with-select"
          v-model="searchCity"
        >
        </el-input>
      </div>
      <p><span id="input-info"></span></p>
    </div>
    <!-- 气泡HTML -->
    <div id="poiBubble" class="bubble" v-show="infoVisible">
      <div class="bubble-tools">
        <span class="bubble-title">{{ title }}</span>
        <span title="关闭" class="bubble-close" @click="close()">x</span>
      </div>
      <div class="bubble-info">
        <table>
          <tr v-for="(item, index) in poiInfo" :key="index">
            <td>{{ item[0] }}</td>
            <td>{{ item[1] }}</td>
          </tr>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "gaodePoiSearch",
  //import引入的组件需要注入到对象中才能使用",
  components: {},
  data() {
    //这里存放数据",
    return {
      //输入提示
      auto: null,
      //经度
      locationLng: null,
      //纬度
      locationLat: null,
      searchCity: null,
      title: null,
      poiInfo: null,
      infoVisible: false
    };
  },
  //监听属性 类似于data概念",
  computed: {},
  //监控data中的数据变化",
  watch: {},
  //方法集合",
  methods: {
    //自动搜索输入框地址
    autoInput() {
      this.$nextTick(() => {
        AMap.plugin("AMap.Autocomplete", function() {
          const autoOptions = {
            city: "全国"
          };
          // 实例化Autocomplete
          // eslint-disable-next-line no-unused-vars
          let autoComplete = new AMap.Autocomplete(autoOptions);
        });
        AMap.event.addListener(this.auto, "select", this.select); //注册监听，当选中某条记录时会触发
      });
    },
    //鼠标点击或者回车选中某个POI信息时触发此事件
    select(resp) {
      //去掉上一次搜索的窗口
      if (this.title != null) {
        this.infoVisible = false;
        window.viewer.trackedEntity = undefined;
        window.viewer.entities.removeById(this.title);
      }
      // console.log(resp.poi);
      let id = resp.poi.id;
      // console.log(JSON.stringify(resp.poi));
      // 把函数从内部作用域指到外面用
      const _this = this;
      // if (resp.poi.location === "") {
      AMap.plugin("AMap.PlaceSearch", function() {
        const placeSearchOptions = {
          city: "全国", // 兴趣点城市
          pageSize: 10, // 单页显示结果条数
          children: 0, //不展示子节点数据
          pageIndex: 1, //页码
          extensions: "base" //返回基本地址信息
        };
        let placeSearch = new AMap.PlaceSearch(placeSearchOptions);
        // 实例化Autocomplete
        // let districtSearch = new AMap.DistrictSearch(districtOptions);
        //详情查询
        placeSearch.getDetails(id, function(status, result) {
          if (status === "complete" && result.info === "OK") {
            // console.log(result.poiList.pois[0]);
            let pois = result.poiList.pois[0];
            _this.viewerflyToLonLat(pois);
          }
        });
      });
    },
    viewerflyToLonLat(pois) {
      let viewer = window.viewer;
      // cesium相机飞行
      viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(
          pois.location.lng,
          pois.location.lat,
          3000
        )
      });
      // let pinBuilder = new Cesium.PinBuilder();
      // let pin = pinBuilder
      //   .fromText(null, Cesium.Color.GREENYELLOW, 48)
      //   .toDataURL();
      // 添加点entity
      let entity = viewer.entities.add({
        id: pois.name,
        position: Cesium.Cartesian3.fromDegrees(
          pois.location.lng,
          pois.location.lat
        ),
        point: {
          color: Cesium.Color.SKYBLUE,
          pixelSize: 12,
          outlineColor: Cesium.Color.YELLOW,
          outlineWidth: 3,
          heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
        }
        // label: {
        //   text: pois.name,
        //   font: "14pt sans-serif",
        //   heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        //   horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
        //   verticalOrigin: Cesium.VerticalOrigin.BASELINE,
        //   fillColor: Cesium.Color.BLACK,
        //   showBackground: true,
        //   backgroundColor: new Cesium.Color(1, 1, 1, 0.7),
        //   backgroundPadding: new Cesium.Cartesian2(8, 4),
        //   disableDepthTestDistance: Number.POSITIVE_INFINITY, // draws the label in front of terrain
        //   pixelOffset: new Cesium.Cartesian2(-20, -50)
        // }
      });
      // entity.description =
      //   "<div style='margin: 0 1rem'>" +
      //   "<p>地址：" +
      //   pois.address +
      //   "</p>" +
      //   "<p>类型：" +
      //   pois.type +
      //   "</p>" +
      //   "<p>联系方式：" +
      //   pois.tel +
      //   "</p>" +
      //   "</div>";
      // 气泡信息
      this.title = pois.name;
      this.poiInfo = [
        ["地址：", pois.address],
        ["类型：", pois.type],
        ["联系方式：", pois.tel]
      ];
      // 传入entiy的坐标xyz
      this.bubblePosition(entity.position._value);
    },
    bubblePosition(entityPosition) {
      let scene = window.viewer.scene;
      let postRender = window.viewer.scene.postRender;
      // let scenePosition = Cesium.Cartesian3.fromDegrees(
      //   pois.location.lng,
      //   pois.location.lat,
      //   100
      // );
      //获取entity的位置，保证获取到准确地经纬度和高度，主要是高度，否则在不同海拔下div定位是相对地面而不失地形
      let scenePosition = entityPosition;
      this.infoVisible = true;
      let infoboxContainer = document.getElementById("poiBubble");
      //窗口位置监听
      postRender.addEventListener(function() {
        // 每一帧都去计算气泡的正确位置
        if (scenePosition) {
          let canvasHeight = scene.canvas.height;
          // console.log(canvasHeight);
          let windowPosition = new Cesium.Cartesian2();
          Cesium.SceneTransforms.wgs84ToWindowCoordinates(
            scene,
            scenePosition,
            windowPosition
          );
          infoboxContainer.style.bottom =
            canvasHeight - windowPosition.y + 100 + "px";
          infoboxContainer.style.left = windowPosition.x + "px";
        }
      });
    },
    //清除方法
    close() {
      this.infoVisible = false;
      window.viewer.trackedEntity = undefined;
      window.viewer.entities.removeById(this.title);
    }
  },
  //生命周期 - 创建之前",数据模型未加载,方法未加载,html模板未加载
  beforeCreate() {},

  //生命周期 - 创建完成（可以访问当前this实例）",数据模型已加载，方法已加载,html模板已加载,html模板未渲染
  created() {},
  //生命周期 - 挂载之前",html模板未渲染
  beforeMount() {},

  //生命周期 - 挂载完成（可以访问DOM元素）",html模板已渲染
  mounted() {
    this.auto = new AMap.Autocomplete({
      input: "tipinput"
    });
    this.autoInput();
  },

  //生命周期 - 更新之前",数据模型已更新,html模板未更新
  beforeUpdate() {},
  //生命周期 - 更新之后",数据模型已更新,html模板已更新
  updated() {},
  //生命周期 - 销毁之前",
  beforeDestroy() {
    this.close();
  },
  destroyed() {},
  //生命周期 - 销毁完成",
  //如果页面有keep-alive缓存功能，这个函数会触发",
  activated() {}
};
</script>

<style scoped>
@import "https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css";
.gaodePoiSearch {
  position: relative;
  width: 100%;
}
.gaodePoiSearch .info {
  position: absolute;
  z-index: 1000;
  top: 20px;
  right: 4rem;
  padding: 0.5rem 1rem;
  background-color: rgba(0, 0, 0, 0.2);
}
.bubble {
  position: fixed;
  min-width: 300px;
  overflow: hidden;
  z-index: 1000;
  color: white;
  /*background-color: rgba(17, 131, 255,.6);*/
  /*border: darkblue 1px solid;*/
  padding: 20px 30px;
  background: linear-gradient(to left, #ffffff, #ffffff) left top no-repeat,
    linear-gradient(to bottom, #ffffff, #ffffff) left top no-repeat,
    linear-gradient(to left, #ffffff, #ffffff) right top no-repeat,
    linear-gradient(to bottom, #ffffff, #ffffff) right top no-repeat,
    linear-gradient(to left, #ffffff, #ffffff) left bottom no-repeat,
    linear-gradient(to bottom, #ffffff, #ffffff) left bottom no-repeat,
    linear-gradient(to left, #ffffff, #ffffff) right bottom no-repeat,
    linear-gradient(to left, #ffffff, #ffffff) right bottom no-repeat,
    rgba(17, 131, 255, 0.5);
  background-size: 3px 20px, 20px 3px, 3px 20px, 20px 3px;
}

.bubble-tools {
  width: 100%;
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-between;
}
.bubble-title {
  color: rgb(241, 141, 93);
  font-size: 25px;
  margin-bottom: 10px;
}
.bubble-info {
  width: 100%;
  overflow: hidden;
  font-size: 18px;
}
.bubble-close {
  color: white;
  cursor: pointer;
  border: 1px white solid;
  width: 20px;
  height: 20px;
  text-align: center;
}
.bubble-close:hover {
  background-color: rgba(255, 255, 255, 0.6);
  color: black;
}
</style>
